//
//  AppDelegate.m
//  FMS
//
//  Created by Steven on 10/10/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "AppDelegate.h"
#import "CouchBaseLiteLib.h"

#define KEY_AUTH @"d6F3Efeq"
@implementation NSData (AES)

- (NSString *)hexadecimalString {
    /* Returns hexadecimal string of NSData. Empty string if data is empty.   */
    
    const unsigned char *dataBuffer = (const unsigned char *)[self bytes];
    
    if (!dataBuffer)
        return [NSString string];
    
    NSUInteger          dataLength  = [self length];
    NSMutableString     *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
    
    for (int i = 0; i < dataLength; ++i)
        [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
    
    return [NSString stringWithString:hexString];
}

+ (NSData *)dataFromHexString:(NSString *)string
{
    NSMutableData *stringData = [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [string length] / 2; i++) {
        byte_chars[0] = [string characterAtIndex:i*2];
        byte_chars[1] = [string characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [stringData appendBytes:&whole_byte length:1];
    }
    return stringData;
}

@end

@implementation AppDelegate
@synthesize arrayLanguage;
@synthesize lblYourAccount;
@synthesize myIndicatorView;

+ (void) getCompanyId:(NSString*)virtualHost {
    
    [[FMSLib shareClient]getCompanyId:virtualHost successs:^(NSMutableDictionary * response){
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        int companyId = [[response objectForKey:COMPANY_ID] intValue];
        [userDefault setObject:[NSNumber numberWithInt:companyId] forKey:COMPANY_ID];
        
    }failure:^(NSError *error){
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Our server is temporary unavailable. Please retry later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [dialog show];
    }];
}
+ (NSString *)decryptInfo:(NSString *)infoStr error:(NSError *)error{
    NSData *newEncryptedData = [NSData dataFromHexString:infoStr];
    
    NSData *decryptedData = [RNDecryptor decryptData:newEncryptedData
                                        withPassword:KEY_AUTH
                                               error:&error];
    NSString *infoDescrypt = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
    return infoDescrypt;
}

+ (NSString *)encryptInfo:(NSString *)infoStr error:(NSError *)error{
    NSData *encryptedData = [RNEncryptor encryptData:[infoStr dataUsingEncoding:NSUTF8StringEncoding] withSettings:kRNCryptorAES256Settings password:KEY_AUTH error:&error];

    NSString *hexString = [encryptedData hexadecimalString];
    return hexString;
}

- (void) btnBackClick:(id)sender {
    [self.menuController dismissModalViewControllerAnimated:YES];
}

- (void) loginSuccess {
    self.lblYourAccount.text = [[NSUserDefaults standardUserDefaults] objectForKey:USER_EMAIL];
    
    if (_menuController == nil) {
        _menuController = [[MenuHomeViewController alloc] initWithNibName:nil bundle:nil];
    }
    self.window.rootViewController = _menuController;
}

- (void)checkVirtualHost:(NSString *)virtualHost{
    //get companyId
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    [[FMSLib shareClient] getDomainInfo:virtualHost successs:^(NSMutableDictionary *success){
        
        [userDefaults setObject:[success objectForKey:@"username"] forKey:NAME_AUTH];
        [userDefaults setObject:[success objectForKey:@"password"] forKey:PASS_AUTH];
        [userDefaults synchronize];
        
        [[FMSServerAPI shareClient] setUserName:[AppDelegate decryptInfo:[userDefaults objectForKey:NAME_AUTH] error:nil] password:[AppDelegate decryptInfo:[userDefaults objectForKey:PASS_AUTH] error:nil]];
        
    }failure:^(NSError *error){
        [userDefaults setObject:@"" forKey:NAME_AUTH];
        [userDefaults setObject:@"" forKey:PASS_AUTH];
        [userDefaults synchronize];
        
        [[FMSServerAPI shareClient] setUserName:@"" password:@""];
        
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Our server is temporary unavailable. Please retry later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [dialog show];
    }];
}

- (void)checkTimeDurationDB{
    //get companyId
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    [[FMSLib shareClient] getTimeDurationSuccess:^(NSMutableDictionary *success){
        NSLog(@"time = %@",[success objectForKey:@"time"]);
        [userDefaults setObject:[success objectForKey:@"time"] forKey:TIME_DURATION_DB_SERVER];
        //test
//        [userDefaults setObject:[NSNumber numberWithLong:500] forKey:TIME_DURATION_DB_SERVER];
        [userDefaults synchronize];
        
        NSString *currentUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"syncpoint"];
//        currentUrl = @"http://113.160.226.202:5986/fms";
        if (currentUrl != nil && ![currentUrl isEqualToString:@""]) {
            
            [[CouchBaseLiteLib sharedCouchBaseLite] setContinuous:YES];
            [CouchBaseLiteLib sharedCouchBaseLite].syncURL = [NSURL URLWithString:currentUrl];
        }
        
    }failure:^(NSError *error){
        [userDefaults setObject:@"0" forKey:TIME_DURATION_DB_SERVER];
        [userDefaults synchronize];
    }];
}
- (void)btnLogoutClick:(id)sender{
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"logout.title"] message:[dictLanguage objectForKey:@"logout.message"] delegate:self cancelButtonTitle:[dictLanguage objectForKey:@"general.no"] otherButtonTitles:[dictLanguage objectForKey:@"general.yes"], nil];
    [dialog show];
}
+ (UIImage *) imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    //  [[UIColor colorWithRed:222./255 green:227./255 blue: 229./255 alpha:1] CGColor]) ;
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

- (NSString*) getMaintenanceName:(int)_maintenanceType {
    NSString *tmpString = @"";
    switch (_maintenanceType) {
        case PM:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pm"];
            break;
        case CM:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm"];
            break;
        case PMS:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pms"];
            break;
        case CM_Above_Cost_Cap:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-above-cost-cap"];
            break;
        case CM_Not_Under_PMWS:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-not-under-pmws"];
            break;
        case New_Works_Above_70:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-above-70"];
            break;
        case New_Works_Below_70:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-below-70"];
            break;
        default:
            break;
    }
    return tmpString;
}

- (NSString*) getMaintenanceStatus:(int)_statusId {
    NSString *tmpString = @"";
    switch (_statusId) {
        case UPCOMING:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.status.upcoming"];
            break;
        case IN_PROCESS:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.status.in-process"];
            break;
        case COMPLETED:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance.status.complete"];
            break;
        default:
            break;
    }
    return tmpString;
}

- (NSString*) getMaintenanceTypeName:(int)_maintenanceType {
    NSString *tmpString = @"";
    
    switch (_maintenanceType) {
        case PM:
            tmpString = [dictLanguage objectForKey:@"schedule.filter-maintenance-type-pm-work"];
            break;
        case CM:
            tmpString = [dictLanguage objectForKey:@"schedule.filter-maintenance-type-cm-work"];
            break;
        case PMS:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.pms"];
            break;
        case CM_Above_Cost_Cap:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-above-cost-cap"];
            break;
        case CM_Not_Under_PMWS:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.cm-not-under-pmws"];
            break;
        case New_Works_Above_70:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-above-70"];
            break;
        case New_Works_Below_70:
            tmpString = [dictLanguage objectForKey:@"maintenance-mgmt.maintenance-type.new-works-below-70"];
            break;
        default:
            break;
    }
    return tmpString;
}
- (NSInteger)getNumberDateTypeRequirement:(int)typeRequiremnt{
    switch (typeRequiremnt) {
        case MONTHLY:
            return 30;
            break;
        case QUATERLY:
            return 90;
        case YEARLY:
            return 360;
        case TWO_YEARLY:
            return 720;
        case FIVE_YEARLY:
            return 1800;
        default:
            break;
    }
    return 0;
}

- (void) setProgressBar:(float)value {
    [loginVC.myProgressView setProgress:value animated:YES];
}

- (void) setProgressBarHidden:(BOOL)hide {
    loginVC.myProgressView.hidden = hide;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//    //test
//    NSString *inputStr = @"qgs@123";
//    NSString *key = @"d6F3Efeq";
//
//    NSError *error;
//    NSData *encryptedData = [RNEncryptor encryptData:[inputStr dataUsingEncoding:NSUTF8StringEncoding] withSettings:kRNCryptorAES256Settings password:key error:&error];
//
//    NSString *hexString = [encryptedData hexadecimalString];
//    NSLog(@"hex = %@",hexString);
//
//    NSData *newEncryptedData = [NSData dataFromHexString:hexString];
//    
//    NSData *decryptedData = [RNDecryptor decryptData:newEncryptedData
//                                            withPassword:key
//                                                   error:&error];
//
//    NSLog(@"decryptedStr = %@",[[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding]);
//    
//    //end test
//    [AppDelegate decryptInfo:@"02012799eee9d1e926d2eddfd01b709323cb6e3e43f451752ce6c0fef06a96c9075045f798d23d2a8f03f9b530866680bffe983f6bd5d50eb777de63086a0ec2388c5795810c99afff5607c94f059227c78f" error:nil];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    //init language file
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    NSNumber *isInitDesignView = [userDefault objectForKey:@"isInitDesignView"];
    if (isInitDesignView == nil)
        [userDefault setObject:[NSNumber numberWithBool:NO] forKey:@"isInitDesignView"];
    
    NSString *strLang = [userDefault objectForKey:CURRENT_LANGUAGE];
    
    NSString *pathLanguage = [[NSBundle mainBundle] pathForResource:@"Languages" ofType:@"plist"];
    NSDictionary *dictLangTmp = [NSDictionary dictionaryWithContentsOfFile:pathLanguage];
    if (dictLangTmp != nil) {
        [userDefault setObject:dictLangTmp forKey:CURRENT_LANGUAGE_DICT];
        if (arrayLanguage != nil) {
            arrayLanguage = nil;
        }
        BOOL found = NO;
        for (int i = 0; i < [[dictLangTmp allKeys] count]; i++) {
            NSString *key = [[dictLangTmp allKeys] objectAtIndex:i];
            if([key isEqualToString:strLang])
            {
                found = YES;
                arrayLanguage = [dictLangTmp objectForKey:key];
            }
        }
        if(!found && [dictLangTmp count] > 0)
        {
            arrayLanguage = [dictLangTmp objectForKey:@"English"];
            [userDefault setObject:@"English" forKey:CURRENT_LANGUAGE];
        }
        dictLanguage = [arrayLanguage objectAtIndex:0];
    }
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    NSString *serverLink = [userDefault objectForKey:SERVER_KEY];
    
    if (serverLink == nil) {
        serverLink = @"http://fms.qa.qgs.vn";
    }
 
    [userDefault setObject:serverLink forKey:SERVER_KEY];
    [FMSServerAPI changeServerLink:serverLink];
    
    NSString *virtualHost;
    //get virtual host
    NSArray *tmpArray = [serverLink componentsSeparatedByString:@"//"];
    NSEnumerator *nse = [tmpArray objectEnumerator];
    [nse nextObject];
    virtualHost = [nse nextObject];
    [userDefault setObject:virtualHost forKey:VIRTUAL_HOST];
    
    [self checkVirtualHost:virtualHost];
    
    [CouchBaseLiteLib sharedCouchBaseLite];
    
    if ([CouchBaseLiteLib sharedCouchBaseLite].database == nil) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.error-could-not-open-database"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
    }
    //get the first sync
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:@"isLogin"];
    [userDefault setObject:[NSNumber numberWithBool:0] forKey:@"isFirstSync"];
    
//    [self checkTimeDurationDB];
    
    // Override point for customization after application launch.
    loginVC = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    _navigationController = [[UINavigationController alloc] initWithRootViewController:loginVC];
    _navigationController.view.frame = loginVC.view.frame;
    loginVC.view.bounds = loginVC.view.frame;
    
    //add progress view
//    myProgressView = [[ProgressView alloc] initWithFrame:CGRectMake(377, 538, 288, 46)];
//    myProgressView.progress = 0.0;
//    [loginVC.view addSubview:myProgressView];
    
    self.window.rootViewController = _navigationController;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //init tab bar controller
    _tabBarController = [[UITabBarController alloc] init];
    
    //create button Home
    UIButton *btnHome = [UIButton buttonWithType:UIButtonTypeCustom];
    btnHome.frame = CGRectMake(-255,3,44,44);
    [btnHome setImage:[UIImage imageNamed:@"btnHome.png"] forState:UIControlStateNormal];
    btnHome.autoresizingMask = ( UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin );
    [btnHome addTarget:self action:@selector(btnBackClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //set background for UITabbar
//    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 1)];
//    imageView.layer.borderColor = [[UIColor colorWithRed:(float)0/255 green:(float)128/255 blue:(float)233/255 alpha:1] CGColor];
//    imageView.layer.borderWidth = 1.0;
//    imageView.backgroundColor = [UIColor colorWithRed:(float)0/255 green:(float)128/255 blue:(float)233/255 alpha:1];
    UILabel *lbBackground;
    if (SYSTEM_VERSION_LESS_THAN(@"7.0"))
        lbBackground = [[UILabel alloc] initWithFrame:CGRectMake(-1, 0, 1026, 50)];
    else
        lbBackground = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1024, 1)];
    lbBackground.layer.borderColor = APPLE_BLUE_COLOR.CGColor;
    lbBackground.layer.borderWidth = 1;
    lbBackground.backgroundColor = [UIColor whiteColor];
    [_tabBarController.tabBar addSubview:lbBackground];
    lbBackground.layer.zPosition = 11;
    
    [_tabBarController.tabBar addSubview:btnHome];
    _tabBarController.tabBar.backgroundColor = [UIColor whiteColor];
    btnHome.layer.zPosition = 11;
    
    lblYourAccount = [[UILabel alloc] initWithFrame:CGRectMake(636, 14, 240, 22)];
//    lblYourAccount.text = @"vinhpham@gmail.com";
    lblYourAccount.backgroundColor = [UIColor clearColor];
    lblYourAccount.textAlignment = UITextAlignmentRight;
    lblYourAccount.textColor = APPLE_BLUE_COLOR;
    lblYourAccount.font = [UIFont fontWithName:FMS_REGULAR_FONT size:17];
    
    UIButton *btnLogout = [[UIButton alloc] initWithFrame:CGRectMake(900, 10, 120, 30)];
    btnLogout.titleLabel.font = [UIFont fontWithName:FMS_REGULAR_FONT size:17];
    [btnLogout setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 10)];
    [btnLogout setTitleEdgeInsets:UIEdgeInsetsMake(0, -45, 0, 0)];
    [btnLogout setTitleColor:APPLE_BLUE_COLOR forState:UIControlStateNormal];
    [btnLogout setTitle:[dictLanguage objectForKey:@"logout.title"] forState:UIControlStateNormal];
    [btnLogout setImage:[UIImage imageNamed:@"iconLogOut.png"] forState:UIControlStateNormal];
    [btnLogout setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -145)];
    
    [btnLogout addTarget:self action:@selector(btnLogoutClick:) forControlEvents:UIControlEventTouchUpInside];
    lblYourAccount.layer.zPosition = 11;
    btnLogout.layer.zPosition = 11;
    
    myIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    myIndicatorView.frame = CGRectMake(50, 3, 44, 44);
    myIndicatorView.hidesWhenStopped = YES;
    [myIndicatorView startAnimating];
    myIndicatorView.layer.zPosition = 11;
    
//    [_tabBarController.tabBar addSubview:myIndicatorView];
    [_tabBarController.tabBar addSubview:lblYourAccount];
    [_tabBarController.tabBar addSubview:btnLogout];
    
    //set default value for isInspectionFailed
    [userDefault setObject:[NSNumber numberWithBool:NO] forKey:IS_INSPECTION_FAILED];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application didChangeStatusBarFrame:(CGRect)oldStatusBarFrame
{
    [application setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}

#pragma mark - UIAlerview delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        [self.menuController dismissModalViewControllerAnimated:NO];
        [self.navigationController popToRootViewControllerAnimated:NO];
        self.window.rootViewController = self.navigationController;
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:@"isLogin"];
    }
}

@end
